
local assert     = assert
local require    = require
local bit        = bit
local coroutine  = coroutine
local debug      = debug
local io         = io
local pairs      = pairs
local ipairs     = ipairs
local math       = math
local os         = os
local print      = print
local pcall      = pcall
local xpcall     = xpcall
local rawget     = rawget
local rawset     = rawset
local select     = select
local string     = string
local table      = table
local tonumber   = tonumber
local tostring	 = tostring
local error      = error
local type       = type
local unpack     = unpack
local setmetatable = setmetatable
local getmetatable = getmetatable
local ngx = ngx
local next = next

local string_char  = string.char
local string_sub   = string.sub
local string_byte  = string.byte
local string_gsub  = string.gsub
local string_find  = string.find
local string_upper = string.upper
local string_lower = string.lower

local math_fmod   = math.fmod
local math_floor  = math.floor
local math_pow    = math.pow
local math_abs    = math.abs

----数据变量----
local uu         = require("modules.commhm.utils");
local log        = require("modules.commhm.log");
local ns_time    = require("modules.commhm.time");
local ns_network = require("modules.commhm.network");

local CNgxTimerWrap   = require("modules.commhm.ngxTimerWrap" )

local table_insert = table.insert

local table_tostring = table.tostring
local table_loadstring = table.loadstring



local FOO = {
	_VERSION = '0.12.1',

	hostname   = uu.os_exec( "hostname" ),
	keeper_ver = "k_20211222_1f",
};

local gg = FOO;   --这里也可以调用gg


---不能更新的目录  ---排重用
FOO.const_dict_ignore_update_dir = {
	[ "modules/env/" ] = 1,
	[ "modules/env" ]  = 1,
	[ "modules/" ]     = 1,
	[ "modules" ]      = 1,
	[ "comm/" ]        = 1,
	[ "comm" ]         = 1,
	[ "lua/" ]         = 1,
	[ "lua" ]          = 1,
}


---房间服 git modules 的配置地址
FOO.const_code_miniw_room_modules = {
	balance   = 2,
	cluster   = 2,
	conf_svr  = 2,
	dispatch  = 2,
	esproxy   = 2,
	friend    = 2,
	inner_account = 2,
	mail        = 2,
	maintenance = 2,
	manor    = 2,
	picwall  = 2,
	report   = 2,
	room     = 2,
	wordwall = 2
}


---房间服 git modules 的配置地址
FOO.const_code_miniw_room_root = {
	["base/"] = 2,
	["common/"] = 2,
	--["lualib/"] = 2,
}


for k, v in pairs(FOO.const_code_miniw_room_modules) do
	FOO.const_code_miniw_room_root[ 'modules/' .. k .. '/' ] = v
end



----获得rsync的源路径
function FOO.get_code_rsync_name( code_dir_name_, env_ )
	if  FOO.const_code_miniw_room_root[ code_dir_name_ ] then
		if  env_ >= 10 then
			return  ' samba@8.210.144.76::76_haima_code_miniw_room_main'
		else
			return ' samba@120.24.64.132::132_haima_code_miniw_room_r'
		end
	else
		if  env_ >= 10 then
			return  ' samba@8.210.144.76::76_haima_code_miniw_activity_main'
		else
			return ' samba@120.24.64.132::132_haima_code_miniw_activity_r'
		end
	end

	log.error( 'error_code_dir_name_and_env' )
	ngx.exit(0)
end



---- ========================================================
FOO.init = function()
	--FOO.hostname   = uu.os_exec( "hostname" )
end


-- 正常退出
FOO.final = function()
end



---延迟执行一个任务
FOO.timer_at = function( delay_, func_, params_ )
	local timer_ = CNgxTimerWrap:new()
	return timer_:ngx_timer_at( delay_, func_,  params_ )
end


---定期执行一个任务
FOO.timer_every = function( delay_, func_, params_ )
	local timer_ = CNgxTimerWrap:new()
	return timer_:ngx_timer_every( delay_, func_, params_  )
end



-----------------utils-------------------------------------------------------
---按配置文件的名字，获得master的进程pid
function FOO.getMasterPidByConfigName( config_name_ )
	local cmd_ = "ps -ef | grep master | grep -v grep | grep " .. config_name_ .. " | awk '{print $2}'"
	local ret_ = uu.os_exec( cmd_ )
	return tonumber( ret_ ) or 0
end


---按配置文件获得nginx进程的运行信息
function FOO.getOrInfoByConfigName( config_name_ )
	local pid_ = gg.getMasterPidByConfigName( config_name_ )
	if  pid_ > 0 then
		return uu.os_exec_async( "ps -ef | grep nginx | grep -v grep | grep " .. pid_ )
	else
		return ""
	end
end


---获得短名字  sbin/nginx -c conf/openresty_skin_1.conf -p xxxx --> openresty_skin_1
function FOO.private_getShortName( long_name_ )
	local t1_ = uu.split( long_name_, ' ' )

	local full_str_
	---获得整个配置文件路径
	if  t1_ then
		for i=1, #t1_ do
			if  t1_[i] == '-c' and t1_[i+1] and #t1_[i+1]>5 then   ---x.conf
			full_str_ = t1_[i+1]
			end
		end
	end

	---获得短名字    ---conf/openresty_skin_1.conf
	if  full_str_ then
		local t2_ = uu.split( full_str_, '/' )
		if  t2_ and #t2_ > 0 and #t2_[#t2_] > 5 then
			return  t2_[#t2_]
		end
	end

end



------------------------------------------------------
---按格式返回 lua table or json
FOO.return_table = function( t )
	t = t or {};

	if  type(t) ~= 'table' then
		t = { ret=t };
	end

	if  ngx.ctx.m_params.json == '1' then
		--json ajax 跨域
		ngx.header["Access-Control-Allow-Origin"] = "*";
		ngx.header["Server"] = "php";

		--log.debug("return json");
		local jret = uu.table2json( t );
		ngx.say(jret);

	elseif ngx.ctx.m_params.log == '1' then
		--log
		log.debug( "<br><br>=========================return begin========" );
		uu.var_dump(t)
		log.debug( "=========================return end========<br><br>" );

	else
		--lua
		local ret = table_tostring( t );
		ngx.say( ret);
	end
end


--返回一个是否是json的后缀
FOO.get_json_postfix = function()
	if  ngx.ctx.m_params.json and ngx.ctx.m_params.json == '1' then
		return "_json"
	else
		return ""
	end
end


---扫描哪些模块可以更新
function FOO.load_lua_modules_update()
	local ret_ = {}

	local dict_ = uu.table_value_copy( FOO.const_dict_ignore_update_dir )

	---扫描目录1
	local dir_scan_str_ = uu.os_exec_file( 'find ./lua/ -maxdepth 1 -type d | sort' )
	local t_ = uu.split( dir_scan_str_, '\n' )
	for k, v in pairs(t_) do
		if  v and #v > 1 then
			local line_ = uu.trim( v )
			--- ./lua/base
			--- ./lua/common
			--- ./lua/tools
			if  string.sub( line_, 1, 6 ) == './lua/' then
				local dir_ = string.sub( line_, 7 )
				if  #dir_ > 1 and (not dict_[ dir_ ]) then
					ret_[ #ret_ + 1 ] = dir_
					dict_[ dir_ ] = 1
				end
			end
		end
	end

	---扫描目录2
	local dir_scan_str_ = uu.os_exec( 'find ./lua/modules/ -maxdepth 1 -type d | sort' )
	local t_ = uu.split( dir_scan_str_, '\n' )
	for k, v in pairs(t_) do
		if  v and #v > 1 then
			local line_ = uu.trim( v )
			--- ./lua/modules/monitor
			--- ./lua/modules/mult_lang_map
			--- ./lua/modules/mysql_tables
			if  string.sub( line_, 1, 14 ) == './lua/modules/' then
				local dir_ = string.sub( line_, 7 )
				if  #dir_ > 1 and (not dict_[ dir_ ]) then
					ret_[ #ret_ + 1 ] = dir_
					dict_[ dir_ ] = 1
				end
			end
		end
	end

	return ret_
end


return FOO;
